use clap::Parser;
use p2p_project::{
    app::Server,
    cli::{Cli, Command},
};
use std::sync::mpsc::channel;
use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::registry()
        .with(fmt::layer())
        .with(EnvFilter::from_default_env())
        .init();

    let cli = Cli::parse();

    match cli.command {
        Command::Start => {
            // termination handler
            let (term_tx, term_rx) = channel();
            ctrlc::set_handler(move || {
                term_tx.send(()).expect("Failed to send termination signal");
            })?;

            // start server
            let mut server = Server::new(cli.grpc_port, cli.base_path);
            server.start().await?;

            // wait for termination signal
            term_rx.recv()?;

            // stop server
            server.stop().await?;
        }
    }

    Ok(())
}
